package com.whosenet.wb.demo;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by Administrator on 2015/7/29.
 */
public class DesTool {


    private static String mode="DES/ECB/PKCS5Padding";
    private static String key = "08bf46321f863ea1";

    public static String decrypt(String message) throws Exception {
       byte[] bytesrc = convertHexString(message);
        Cipher cipher = Cipher.getInstance(mode);
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);
    }




    public static byte[] encrypt(String message) throws Exception {
        Cipher cipher = Cipher.getInstance(mode);

      //  DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return cipher.doFinal(message.getBytes("UTF-8"));
    }

    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }

        return digest;
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }

        return hexString.toString();
    }


    public static void main(String[] args) {
        try {
            //String s=decrypt("732f56c9a22f03a66ea538dbf8894d242e419701d3410f29");
            String s=decrypt("d91bc739f3105e4f36c98be8e8c232a7d7e099058f92d842634fcd24a95220e42bb644a3c970e30b66a9620f47c517b4");

            System.out.printf(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
